package ltd.newbee.mall.service.impl;

import ltd.newbee.mall.dao.RoleMapper;
import ltd.newbee.mall.dao.UserMapper;
import ltd.newbee.mall.entity.Role;
import ltd.newbee.mall.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public boolean updateRoleMenus(Long roleId, List<Long> menuIds) {
        try {
            // 删除原有权限
            roleMapper.deleteRoleMenuByRoleId(roleId);

            // 添加新权限
            if (menuIds != null && !menuIds.isEmpty()) {
                roleMapper.batchInsertRoleMenu(roleId, menuIds);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("更新角色菜单权限失败: " + e.getMessage());
        }
    }

    public List<Role> getRoleList(Map<String, Object> params) {
        List<Role> roles = roleMapper.selectRoleList(params);
     /*   // 为每个角色设置用户数量和菜单信息
        roles.forEach(role -> {
            int userCount = roleMapper.countUsersByRoleId(role.getRoleId());
        });*/
        return roles;
    }

    public List<Long> getRoleMenuIds(Long roleId) {
        return roleMapper.selectMenuIdsByRoleId(roleId);
    }

    public Role getRoleById(Long roleId) {
        Role role = roleMapper.selectRoleById(roleId);
        if (role != null) {
            List<Long> menuIds = menuService.getMenuIdsByRoleId(roleId);
            role.setMenuIds(menuIds);
        }
        return role;
    }

    @Transactional
    public boolean addRole(Role role) {
        // 检查角色名是否重复
        int count = roleMapper.countByRoleName(role.getRoleName(), null);
        if (count > 0) {
            throw new RuntimeException("角色名称已存在");
        }

        int result = roleMapper.insertRole(role);
        if (result > 0 && role.getMenuIds() != null && !role.getMenuIds().isEmpty()) {
            menuService.updateRoleMenus(role.getRoleId(), role.getMenuIds());
        }
        return result > 0;
    }

    @Transactional
    public boolean updateRole(Role role) {
        // 检查角色名是否重复（排除自己）
        int count = roleMapper.countByRoleName(role.getRoleName(), role.getRoleId());
        if (count > 0) {
            throw new RuntimeException("角色名称已存在");
        }

        int result = roleMapper.updateRole(role);
        if (result > 0 && role.getMenuIds() != null) {
            menuService.updateRoleMenus(role.getRoleId(), role.getMenuIds());
        }
        return result > 0;
    }

    @Transactional
    public boolean deleteRole(Long roleId) {
        // 检查是否有用户使用该角色
        int userCount = roleMapper.countUsersByRoleId(roleId);
        if (userCount > 0) {
            throw new RuntimeException("该角色下有用户使用，无法删除");
        }

        // 删除角色菜单权限
        menuService.updateRoleMenus(roleId, null);
        // 删除角色
        return roleMapper.deleteRole(roleId) > 0;
    }

    public List<User> getUsersByRoleId(Long roleId) {
        return userMapper.selectUsersByRoleId(roleId);
    }
}
